<?php

require_once "AbstractHelper.php";

class LangSwitcher extends AbstractHelper{

    private $langParam;
    private $useCookie;

    public function __construct(Controller $owner, $langParam = "lang", $useCookie = true){
        $this->langParam = $langParam;
        $this->useCookie = $useCookie;
        $owner->addHelper($this);
        $owner->reserveParameter($langParam);
    }

    public function createLanguageAddress($lang){
        return $this->owner->createReloadAddress(array($this->langParam => $lang));
    }

    public function process(){
        $request = $this->owner->getRequest();
        $paramLang = $request->getParameter($this->langParam);
        $cookieLang = $request->getCookie($this->langParam);
        $lang = $paramLang;
        if($this->useCookie && $paramLang !== null && $cookieLang !== $paramLang)
            setcookie($this->langParam, $paramLang, time() + 60*60*24*30);
        if($paramLang === null && $cookieLang !== null)
            $lang = $cookieLang;
        TextBinder::setLanguage($lang);
    }

}
?>
